package org.sqlproc.sample.catalog.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.sqlproc.engine.SqlEngine;
import org.sqlproc.engine.SqlEngineLoader;
import org.sqlproc.engine.SqlOrder;
import org.sqlproc.sample.catalog.form.ItemForm;
import org.sqlproc.sample.catalog.model.Item;
import org.sqlproc.sample.catalog.to.ItemTO;

public class ItemDao extends HibernateDaoSupport {

    protected SqlEngineLoader sqlEngines;

    public Item findById(Serializable id) {
        Item entity = (Item) getHibernateTemplate().get(Item.class, id);
        return entity;
    }

    public Item store(Item entity) {
        entity = getHibernateTemplate().merge(entity);
        getHibernateTemplate().flush();
        return entity;
    }

    public void remove(Serializable entityId) {
        Item entity = findById(entityId);
        if (entity != null) {
            remove(entity);
        }
    }

    protected void remove(Item entity) {
        getHibernateTemplate().delete(entity);
        getHibernateTemplate().flush();
    }

    public List<ItemTO> find(ItemForm criteria) {
        Session session = getSessionFactory().getCurrentSession();
        return getSqlEngine("ITEMS").query(session, ItemTO.class, criteria, null,
                SqlOrder.getOrder(criteria.getOrder()), 0, criteria.getCount(), criteria.getFirst());
    }

    public int findCount(ItemForm criteria) {
        Session session = getSessionFactory().getCurrentSession();
        return getSqlEngine("ITEMS").queryCount(session, criteria);
    }

    public SqlEngine getSqlEngine(String name) {
        return sqlEngines.getSqlEngine(name);
    }

    public void setSqlEngines(SqlEngineLoader sqlEngines) {
        this.sqlEngines = sqlEngines;
    }
}
